//
//  ComposeViewController.m
//  Weibo
//
//  Created by Anasue on 9/11/15.
//  Copyright (c) 2015 Anasue. All rights reserved.
//

#import "ComposeViewController.h"
#import "EmotionTextView.h"
#import "ComposeToolBar.h"
#import "AFNetworking.h"
#import "Status.h"
#import "AccountTool.h"
#import "Account.h"
#import "MBProgressHUD+MJ.h"
#import "ComposePhotosView.h"
#import "SendStatusParam.h"
#import "SendStatusResult.h"
#import "StatusTool.h"
#import "ComposeToolBar.h"
#import "EmotionKeyBoard.h"
#import "Emotion.h"


@interface ComposeViewController ()<UITextViewDelegate,UINavigationControllerDelegate,ComposeToolBarDelegate,UIImagePickerControllerDelegate>
@property (nonatomic, weak) EmotionTextView *textView;
@property (nonatomic, weak) ComposeToolBar *toolBar;
@property (nonatomic, weak) ComposePhotosView *photosView;
@property (nonatomic, assign,getter = isChangingKeyboard) BOOL changingKeyboard;

@end

@implementation ComposeViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    //添加导航栏
    [self setupNavBar];
    
    //添加textView编辑框
    [self setupTextView];
    
    //添加工具条
    [self setupToolBar];
    
    //添加photosView图片
    [self setupPhotosView];
    
    //接收通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didSelectedEmotion:) name:EmotionDidSelectNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didDeletedEmotion:) name:EmotionDidDeleteNotification object:nil];
}
/**
 *  添加photosView图片
 */
- (void)setupPhotosView
{
    ComposePhotosView *photosView = [[ComposePhotosView alloc]init];
    photosView.width = self.textView.width;
    photosView.height = self.textView.height;
    photosView.y = 100;
    [self.textView addSubview:photosView];
    self.photosView = photosView;
}

/**
 *  添加工具条
 */
- (void)setupToolBar
{
    ComposeToolBar *toolBar = [[ComposeToolBar alloc]init];
    toolBar.x = 0;
    toolBar.width = self.view.size.width;
    toolBar.height = 44;
    toolBar.y = self.view.size.height - toolBar.height;
    self.toolBar = toolBar;
    toolBar.delegate = self;
    [self.view addSubview:self.toolBar];
    
}

- (void)setupNavBar
{
    NSString *name = [AccountTool account].name;
//    Log(@"%@",name);
    if (name) {
        NSString *prefix = @"发微博";
        NSString *text = [NSString stringWithFormat:@"%@\n%@",prefix,name];
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:text];
        [string addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13] range:[text rangeOfString:prefix]];
        [string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:[text rangeOfString:name]];
        UILabel *titleLabel = [[UILabel alloc]init];
        titleLabel.attributedText = string;
        titleLabel.numberOfLines = 0;
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.width = 100;
        titleLabel.height = 44;
        self.navigationItem.titleView = titleLabel;
    }else {
    self.title = @"发微博";
    }
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancel)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"发送" style:UIBarButtonItemStyleDone target:self action:@selector(send)];
    self.navigationItem.rightBarButtonItem.enabled = NO;
}

- (void)setupTextView
{
    //1.创建textView
    EmotionTextView *textView = [[EmotionTextView alloc]init];
    textView.alwaysBounceVertical = YES;
    //2.设置textView的frame
    textView.frame = self.view.bounds;
    
    //3.添加textView到控制器中
    [self.view addSubview:textView];
    self.textView = textView;
    textView.delegate = self;
    //4.设置文字
    textView.placeholder = @"分享新鲜事...";
    textView.font = [UIFont systemFontOfSize:15];
    
    //5.监听键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.textView becomeFirstResponder];
}

- (void)cancel
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)send
{
    if (self.photosView.images.count) {
    [self sendStatusWithImage];
    }else{
    [self sendStatusWithoutImage];
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
/**
 *  发送有图片微博
 */
- (void)sendStatusWithImage
{
    //1.创建管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    //参数
    /**
     access_token	false	string	采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得。
     status	true	string	要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
     */
    //json字典
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"access_token"] = [AccountTool account].access_token;
    params[@"status"] = self.textView.text;
    //pic	true	binary	要上传的图片，仅支持JPEG、GIF、PNG格式，图片大小小于5M。
    
    //2.发送数据请求
    [mgr POST:@"https://upload.api.weibo.com/2/statuses/upload.json" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        UIImage *image = [self.photosView.images firstObject];
        NSData *data = UIImageJPEGRepresentation(image, 1.0);
        [formData appendPartWithFileData:data name:@"pic" fileName:@"status.jpg" mimeType:@"image/jpeg"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        Log(@"发送成功");
        [MBProgressHUD showSuccess:@"发送成功"];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        Log(@"发送失败,%@",error);
        [MBProgressHUD showError:@"发送失败"];
    }];
}
/**
 *  发送无图片微博
 */
- (void)sendStatusWithoutImage
{
//    Log(@"%@",self.textView.realText);
    SendStatusParam *param = [SendStatusParam param];
    param.status = self.textView.realText;
    [StatusTool sendStatusesWithParams:param success:^(SendStatusResult *result) {
        Log(@"发送成功");
        [MBProgressHUD showSuccess:@"发送成功"];

    } failure:^(NSError *error) {
        Log(@"发送失败,%@",error);
        [MBProgressHUD showError:@"发送失败"];

    }];
  
//    //1.创建管理者
//    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
//    
//    //参数
//    /**
//    access_token	false	string	采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得。
//    status	true	string	要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
//    */
//    //json字典
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    params[@"access_token"] = [AccountTool account].access_token;
//    params[@"status"] = self.textView.text;
//    
//    
//    //2.发送数据请求
//    [mgr POST:@"https://api.weibo.com/2/statuses/update.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
//        Log(@"发送成功");
//        [MBProgressHUD showSuccess:@"发送成功"];
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        Log(@"发送失败,%@",error);
//        [MBProgressHUD showError:@"发送失败"];
//
//    }];
}

#pragma mark - keyboard通知
- (void)keyboardWillShow:(NSNotification *)note
{

    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duration animations:^{
        //取出键盘高度
        CGRect keyboardF = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        CGFloat keyboardY =keyboardF.size.height;
        self.toolBar.transform = CGAffineTransformMakeTranslation(0, -keyboardY);
    }];
}

- (void)keyboardWillHide:(NSNotification *)note
{
    if (self.isChangingKeyboard) return;

    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        self.toolBar.transform = CGAffineTransformIdentity;
    }];

}

#pragma mark - ComposeToolBarDelegate
- (void)composeTool:(ComposeToolBar *)toolBar didClickBtn:(ComposeToolBarButtonType)buttonType
{
    switch (buttonType) {
        case ComposeToolBarButtonCamera:
            [self openCamera];
            break;
        case ComposeToolBarButtonPicture:
            [self openAlbum];
            break;
        case ComposeToolBarButtonMention:
            [self openMention];
            break;
        case ComposeToolBarButtonTrend:
            [self openTrend];
            break;
        case ComposeToolBarButtonEmotion:
            [self openEmotion];
            break;
        default:
            break;
    }
}


- (void)openCamera
{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        return;
    UIImagePickerController *ipc = [[UIImagePickerController alloc]init];
    ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
    ipc.delegate = self;
    [self presentViewController:ipc animated:YES completion:nil];


}

- (void)openAlbum
{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
        return;
    UIImagePickerController *ipc = [[UIImagePickerController alloc]init];
    ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    ipc.delegate = self;
    [self presentViewController:ipc animated:YES completion:nil];
}

- (void)openMention
{}

- (void)openTrend
{}

- (void)openEmotion
{
    self.changingKeyboard = YES;
    if (self.textView.inputView) {
        self.textView.inputView = nil;
        self.toolBar.showEmotionButton = YES;
    }else{
        EmotionKeyBoard *keyboard = [[EmotionKeyBoard alloc]init];
        keyboard.bounds = CGRectMake(0, 0, 320, 248);
        self.textView.inputView = keyboard;
        self.toolBar.showEmotionButton = NO;
    }
    [self.textView resignFirstResponder];
    self.changingKeyboard = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.textView becomeFirstResponder];
    });

}

#pragma mark - 通知
- (void)didSelectedEmotion:(NSNotification *)note
{
    Emotion *emotion = note.userInfo[SelectedEmotion];
    [self.textView appendEmotion:emotion];
    [self textViewDidChange:self.textView];
}

- (void)didDeletedEmotion:(NSNotification *)note
{
    [self.textView deleteBackward];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //关闭控制器
    [picker dismissViewControllerAnimated:YES completion:nil];
    //选取图片
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    //将图片添加进将要显示的View上
    [self.photosView addImage:image];
}


#pragma mark - UITextViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

- (void)textViewDidChange:(UITextView *)textView
{
//    self.navigationItem.rightBarButtonItem.enabled = textView.attributedText.length != 0;
    self.navigationItem.rightBarButtonItem.enabled = self.textView.hasText;
}




@end
